// pages/index/home.js
const App = getApp()
const citySelector = requirePlugin('citySelector')


import Kits from '../../utils/kits'


Component({
  options: {
    addGlobalClass: true,
  },
  properties: {

  },
  data: {
    init: false,
    nowloc: {
      code: '',
      city: '加载中',
      name: '正在获取位置',
      locs: '',
      time: 0,
    },
    begin: {
      value: undefined,
      year: '',
      date: '',
      time: '',
    },
    close: {
      value: undefined,
      year: '',
      date: '',
      time: '',
    },
    hdays: '',

    onsite: false,

    onsite_area: '',
    onsite_addr: '',
    onsite_locs: '',

    advs: [],
    cars: [],
    summ: {}
  },

  lifetimes: {
    attached() {
      this.execLoad()
      wx.sub('ReloadUserFin', this, () => {
        this.execLoadFin()
      })
      this.execLoadFin()
    },
    detached() {
      citySelector.clearCity()
      wx.cancel('ReloadUserFin', this)
    },
  },
  pageLifetimes: {
    show() {
          const selectedCity = citySelector.getCity() // 选择城市后返回城市信息对象，若未选择返回null
          if (selectedCity) {
            let nowloc = this.data.nowloc
            nowloc.code = selectedCity.id
            nowloc.city = selectedCity.name
            nowloc.name = '正在获取位置'
            nowloc.time = new Date().getTime()
            nowloc.locs = `${selectedCity.location.longitude},${selectedCity.location.latitude}`

            this.setData({
              nowloc: nowloc
            })
            console.log(this.data.nowloc, "啊呃呃额")
            this.execReadLocation(nowloc.locs)
          }
    }
  },
  methods: {
    execLoad() {
      let now = Kits.getNextTime(new Date().getTime())
      this.doSetDates(now, now.addDays(2))
      App.doPost({
        uri: '/app/base/data/adv',
        body: {
          advp: 'IDX_BANNER',
          size: 5
        },
        fnSucc: resp => {
          this.setData({
            init: true,
            advs: resp.data.items
          })
        }
      })
      if (this.data.nowloc.locs == '' || Math.abs(this.data.nowloc.time - new Date().getTime()) > 10 * 60 * 1000) {
        App.doPost({
          uri: '/comm/tool/ip/location',
          body: {},
          fnSucc: resp => {
            let nowloc = this.data.nowloc
            nowloc.code = resp.data.code
            nowloc.city = resp.data.city
            if (nowloc.locs == '' && resp.data.locs != '') {
              nowloc.locs = resp.data.locs
              this.execReadLocation(nowloc.locs)
            }
            this.setData({
              nowloc: nowloc
            })
          }
        })
      }
      this.doLocation()
    },
    execLoadFin() {
      App.doPost({
        uri: '/app/wallet/fin/summary',
        body: {},
        fnSucc: resp => {
          resp.data.couponStr = (resp.data.coupon) + ''
          resp.data.amountStr = Kits.fmtMoneyString(resp.data.amount)
          resp.data.settleStr = Kits.fmtMoneyString(resp.data.settle)
          resp.data.depositStr = Kits.fmtMoneyString(resp.data.deposit)
          this.setData({
            summ: resp.data
          })
        }
      })
    },
    doLoadCars(city) {
      if (this.data.loadcar) {
        return
      }
      this.data.loadcar = true
      App.doPost({
        uri: '/app/base/biz/car/recommend',
        body: {
          city: city,
          size: 8
        },
        fnSucc: resp => {
          resp.data.items.forEach(item => {
            item.price.pdpStr = Kits.fmtMoneyString(item.price.pdp)
            item.price.pmpStr = Kits.fmtMoneyString(item.price.pmp)
            item.price.mdpStr = Kits.fmtMoneyString(item.price.mdp)
            item.price.depositStr = Kits.fmtMoneyString(item.price.deposit)
            item.price.dispStr = Kits.fmtMoneyString(item.price.disp)
          })
          this.setData({
            cars: resp.data.items
          })
        },
        fnComp: () => {
          this.data.loadcar = false
        }
      })
    },
    doLocation() {
      let lastTime = parseInt(wx.getStorageSync('App.Cache.NowLocsTime') + '')
      let lastLocs = wx.getStorageSync('App.Cache.NowLocsInfo')
      if (lastLocs != '' && new Date().getTime() - lastTime < 2 * 60 * 1000) {
        // 小于5分钟
        let nowloc = this.data.nowloc
        nowloc.locs = lastLocs
        this.setData({
          nowloc: nowloc
        })
        this.execReadLocation(nowloc.locs)
        return
      }
      wx.getLocation({
        type: 'gcj02',
        success: (res) => {
          let locs = `${res.longitude.toFixed(6)},${res.latitude.toFixed(6)}`
          wx.setStorageSync('App.Cache.NowLocsInfo', locs)
          wx.setStorageSync('App.Cache.NowLocsTime', new Date().getTime())
          let nowloc = this.data.nowloc
          nowloc.locs = locs
          this.setData({
            nowloc: nowloc
          })
          this.execReadLocation(nowloc.locs)
        }
      })
    },
    // 读取位置信息
    execReadLocation(locs) {
      if (locs == '') {
        return
      }
      App.doPost({
        uri: '/comm/tool/locs/info',
        body: {
          locs: locs
        },
        fnSucc: resp => {
          let nowloc = this.data.nowloc
          nowloc.code = resp.data.city
          nowloc.locs = locs
          nowloc.city = resp.data.area.city
          nowloc.name = resp.data.name
          nowloc.time = new Date().getTime()
          this.setData({
            nowloc: nowloc,
            onsite_addr: resp.data.name,
            onsite_area: resp.data.area.code + "",
            onsite_locs: locs
          })
          this.doLoadCars(nowloc.code)
        },
        fnFail: () => {
          Util.Toast.fail('未知地点信息')
        }
      })
    },
    // 选择城市
    doSelectCity() {
      const key = App.Global.QmapKey // 使用在腾讯位置服务申请的key
      const referer = App.Global.Title // 调用插件的app的名称
      // const hotCitys = '' // 用户自定义的的热门城市
      wx.navigateTo({
        url: `plugin://citySelector/index?key=${key}&referer=${referer}`,
      })
    },
    // 选择地点
    doSelectLocs() {
      let lng = this.data.onsite_locs ? parseFloat(this.data.onsite_locs.split(',')[0]) : undefined
      let lat = this.data.onsite_locs ? parseFloat(this.data.onsite_locs.split(',')[1]) : undefined
      wx.chooseLocation({
        longitude: lng,
        latitude: lat,
        success: (res) => {
          let locs = res.longitude.toFixed(6) + ',' + res.latitude.toFixed(6)
          this.execReadLocation(locs)
        },
        fail: (err) => {
          console.log(err)
        }
      })
    },
    // 设置日期
    doSetDates(beginTime, closeTime) {
      let begin = {
        value: beginTime.getTime(),
        year: beginTime.format('yyyy'),
        date: beginTime.format('MM月dd日'),
        time: beginTime.format('HH:mm'),
      }
      let close = {
        value: closeTime.getTime(),
        year: closeTime.format('yyyy'),
        date: closeTime.format('MM月dd日'),
        time: closeTime.format('HH:mm'),
      }
      this.setData({
        begin: begin,
        close: close,
        hdays: Kits.getDateMemo(beginTime, closeTime)
      })
    },
    // 跳转页面
    toPage(e) {
      wx.navigateTo({
        url: e.currentTarget.dataset.uri
      })
    },
    // 跳转选择日期界面
    toSelectDate() {
      wx.navigateTo({
        url: `/pages/order/calendar?carid=&begin=${this.data.begin.value}&close=${this.data.close.value}`,
        events: {
          enter: (e) => {
            this.doSetDates(new Date(e.begin), new Date(e.close))
          }
        }
      })
    },
    // 去下单
    toCreateOrder(e) {
      let car = e.currentTarget.dataset.car
      wx.navigateTo({
        url: `/pages/order/create?carid=${car.id}&begin=${this.data.begin.value}&close=${this.data.close.value}&onsite=${this.data.onsite}&onsite_area=${this.data.onsite_area}&onsite_locs=${this.data.onsite_locs}&onsite_addr=${this.data.onsite_addr}`,
      })
    },
    // 去车型选择
    toCars() {
      wx.navigateTo({
        url: `/pages/home/cars?begin=${this.data.begin.value}&close=${this.data.close.value}&onsite=${this.data.onsite}&area=${this.data.onsite_area}&locs=${this.data.onsite_locs}&addr=${this.data.onsite_addr}&city=${this.data.nowloc.code}`,
      })
    }
  }
})